export const request = (options) => {
	return new Promise((resolve, reject) => {
		const baseUrl = 'http://192.168.31.71:9999/';
		
		// 检查登录状态
		const token = uni.getStorageSync('token');
		if (!token && options.url !== 'owner-server/owner/login/phone' && options.url !== 'owner-server/owner/login/sendVerifyCode') {
			console.log("111");
			uni.showModal({
				title: '提示',
				content: '请先登录',
				showCancel: false,
				success: () => {
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			});
			reject(new Error('未登录'));
			return;
		}

		uni.request({
			url: baseUrl + options.url,
			method: options.method || 'GET',
			data: options.data || 0,
			header: {
				'Content-Type': 'application/json',
				'token': token
			},
			success: (res) => {
				if (res.statusCode === 200) {
					// 如果是登录请求，保存token
					if (options.url === 'owner/login/phone' && res.data.code === 200) {
						uni.setStorageSync('token', res.data.data.token);
					}
					resolve(res.data);
				} else if (res.statusCode === 401) {
					// token过期或无效
					uni.removeStorageSync('token');
					uni.showModal({
						title: '提示',
						content: '登录已过期，请重新登录',
						showCancel: false,
						success: () => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}
					});
					reject(new Error('登录已过期'));
				} else {
					reject(new Error(`请求失败: ${res.statusCode}`));
				}
			},
			fail: (err) => {
				console.error('请求失败:', err);
				uni.showModal({
					title: '提示',
					content: '网络请求失败，请检查网络连接',
					showCancel: false
				});
				reject(err);
			}
		});
	});
};

export default request;